package cn.com.bsoft.wePortal.partner

import cn.com.bsoft.kotlinEx.AllOpen
import cn.com.bsoft.wePortal.config.service.ConfigService
import cn.com.bsoft.wePortal.partner.model.PartnerProperties
import cn.com.bsoft.wePortal.partner.service.DefaultPartnerService
import cn.com.bsoft.wePortal.partner.service.PartnerService
import cn.com.bsoft.wePortal.partner.support.PartnerFilter
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.http.MediaType


@AllOpen
@Configuration
@EnableJpaRepositories(basePackages = arrayOf("cn.com.bsoft.wePortal.partner.dao"))
@EntityScan("cn.com.bsoft.wePortal.partner.entity")
@EnableConfigurationProperties(PartnerProperties::class)
class PartnerConfiguration {

    @Autowired
    lateinit var configService:ConfigService

    @Bean
    @ConditionalOnMissingBean
    fun partnerService(): PartnerService {
        return DefaultPartnerService()
    }


    @Bean
    fun partnerFilter(properties: PartnerProperties): FilterRegistrationBean<PartnerFilter> {

        val mimeTypes = properties.mimeTypes.map {
            MediaType.parseMediaType(it)
        }

        val filter = PartnerFilter(if (mimeTypes.isNotEmpty()) mimeTypes else  listOf(MediaType.APPLICATION_JSON))

        filter.partnerProperties = properties
        filter.configService = configService

        val registration = FilterRegistrationBean<PartnerFilter>()

        registration.filter = filter

        properties.paths?.forEach {
            registration.addUrlPatterns(it)
        }

        return registration
    }

}